package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFegin;
import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDto;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.model.search.pojo.ApUserSearch;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by ZYJ on 2021/6/8 22:15
 */
@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    BehaviorFegin behaviorFeign;
    /**
     * 保存用户搜索历史记录
     * @param userSearchDto
     */
    @Override
    @Async("taskExecutor")
    public void insert(UserSearchDto userSearchDto) {
        String searchWords = userSearchDto.getSearchWords();
        Integer entryId = userSearchDto.getEntryId();
        if(entryId == null || StringUtils.isBlank(searchWords)){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询实体
        ApBehaviorEntry behaviorEntry = behaviorFeign.findBehaviorEntry(entryId, userSearchDto.getEquipmentId());
        if (behaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 查询当前用户搜索的关键词是否存在
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(
                Criteria.where("entryId").is(entryId)
                        .and("keyword").is(searchWords)), ApUserSearch.class);

        //3.1 存在则更新最新时间，更新状态
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.2 不存在则新增
        apUserSearch = new ApUserSearch();
        apUserSearch.setEntryId(entryId);
        apUserSearch.setKeyword(searchWords);
        apUserSearch.setCreatedTime(new Date());
        mongoTemplate.save(apUserSearch);

    }
    /**
     * 搜索历史记录 显示10条 按照时间倒序
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDto userSearchDto) {

        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry = behaviorFeign.findBehaviorEntry(user == null ? null : user.getId(), userSearchDto.getEquipmentId());
        if(behaviorEntry != null){
            List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(Criteria
                    .where("entryId").is(behaviorEntry.getEntryId()))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    .limit(10), ApUserSearch.class);
            return ResponseResult.okResult(apUserSearchList);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 删除历史记录
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if(historySearchDto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry behaviorEntry = behaviorFeign.findBehaviorEntry(user == null ? null : user.getId(), historySearchDto.getEquipmentId());
         if (behaviorEntry == null){
             return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
         }
         this.mongoTemplate.remove(Query.query(Criteria.where("_id").is(historySearchDto.getId()).and("entryId").is(behaviorEntry.getEntryId())),ApUserSearch.class);

        return ResponseResult.okResult();
    }
}
